package com.usian.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.discovery.converters.Auto;
import com.usian.CartFeign;
import com.usian.SsoFeign;
import com.usian.config.RedisClient;
import com.usian.pojo.TbItem;
import com.usian.pojo.TbUser;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/frontend/sso")
public class SSOController {

    @Autowired
    private SsoFeign ssoFeign;

    @Autowired
    private CartFeign cartFeign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Autowired
    private RedisClient redisClient;

    /**
     * 用户注册信息校验
     *
     * @param checkValue
     * @param checkFlag
     * @return
     */
    @RequestMapping("/checkUserInfo/{checkValue}/{checkFlag}")
    public Result checkUserInfo(@PathVariable String checkValue,@PathVariable int checkFlag){

        boolean bool = ssoFeign.checkUserInfo(checkValue,checkFlag);
        if(bool){
            return Result.ok("OK");
        }
        return Result.error("校验失败");
    }

    /**
     * 用户注册
     *
     * @param tbUser
     * @return
     */
    @RequestMapping("/userRegister")
    public Result userRegister(TbUser tbUser){

        boolean bool = ssoFeign.userRegister(tbUser);
        if(bool){
            return Result.ok("OK");
        }
        return Result.error("注册失败");
    }


    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/userLogin")
    public Result userLogin(String username , String password, HttpServletRequest request, HttpServletResponse response){

        Map map  = ssoFeign.userLogin(username,password);
        if(map.size()>0){

            //把cookie中取出来
            String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY, true);
            if(StringUtils.isNotBlank(cookieValue)){

                Map<String, Object> cookieMap = JsonUtils.jsonToMap(cookieValue, TbItem.class);

                Map<String, Object>  redisMap = cartFeign.getCartByUserId(map.get("userid").toString());

                Set<String> keySet = cookieMap.keySet();

                for(String key : keySet){

                    TbItem cookieTbItem = (TbItem)cookieMap.get(key);

                    Set<String> redisKey = redisMap.keySet();

                    if(redisKey.size()>0){
                        for(String rk : redisKey){

                            if(rk.equals(key)){

                                ObjectMapper objectMapper =new ObjectMapper();
                                TbItem tbItem =objectMapper.convertValue(redisMap.get(rk),TbItem.class);
                                tbItem.setNum(tbItem.getNum()+cookieTbItem.getNum());

                                redisMap.put(tbItem.getId().toString(),tbItem);

                                //cookie 删掉   redis 跟新

                                redisClient.hset("CART_REDIS_KEY",map.get("userid").toString(),redisMap);
                                CookieUtils.deleteCookie(request,response,CART_COOKIE_KEY);
                            }else{

                                redisMap.put(cookieTbItem.getId().toString(),cookieTbItem);
                                redisClient.hset("CART_REDIS_KEY",map.get("userid").toString(),redisMap);
                                CookieUtils.deleteCookie(request,response,CART_COOKIE_KEY);
                            }

                        }
                    }else{
                        redisMap.put(cookieTbItem.getId().toString(),cookieTbItem);
                        redisClient.hset("CART_REDIS_KEY",map.get("userid").toString(),redisMap);
                        CookieUtils.deleteCookie(request,response,CART_COOKIE_KEY);
                    }
                }

            }else{
                System.out.println("cookie 无效  ");
            }

            return Result.ok(map);
        }
        return Result.error("登录失败");
    }


    /**
     * 校验用户的token有效时间
     *
     * @param token
     * @return
     */
    @RequestMapping("/getUserByToken/{token}")
    public Result getUserByToken(@PathVariable String token ){

        int resultNum = ssoFeign.getUserByToken(token);
        if(resultNum>0){
            return Result.ok("ok");
        }
        return Result.error("失败");
    }

    /**
     * 用户退出
     *
     * @param token
     * @return
     */
    @RequestMapping("/logOut")
    public Result logOut(@RequestParam String token ){

        int resultNum = ssoFeign.logOut(token);
        if(resultNum>0){
            return Result.ok("ok");
        }
        return Result.error("退出失败");
    }


}
